package com.wish.g1.file.controller;

import com.bw.springboot.starter.upload.model.Chunk;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import com.wish.g1.common.core.web.domain.AjaxResult;
import com.wish.g1.file.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.wish.g1.common.core.domain.R;
import com.wish.g1.common.core.utils.file.FileUtils;
import com.wish.g1.system.api.domain.SysFile;

import java.util.concurrent.TimeUnit;

/**
 * 文件请求处理
 *
 * @author wish
 */
@RefreshScope
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private FileService fileService;

    /**
     * 大文件分片上传
     * @param chunk
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("postFileUpload")
    public AjaxResult postFileUpload(@ModelAttribute Chunk chunk){
        fileService.postFileUpload(chunk);
        if (chunk.getTotalChunks().equals(chunk.getChunkNumber())) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            FileResult fileResult = fileService.mergeFile(chunk);
            //return AjaxResult(200,"合并成功！",fileResult);
            return new AjaxResult(200,"合并成功！",fileResult);
        }
        log.info("文件上传成功");
        return AjaxResult.success();
    }

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}
